package model

import (
	"autoclave/utils/tools"
	"database/sql/driver"
	"fmt"
	"time"
)

type QueryData struct {
	PageIndex int    `json:"page" form:"page"`
	PageSize  int    `json:"size" form:"size"`
	Search    string `json:"search" form:"search"`
	Status    string `json:"status" form:"status"`
	Type      string `json:"type" form:"type"`
	Date      string `json:"date" form:"date"`
	StartTime string `json:"start_time" form:"start_time"`
	EndTime   string `json:"end_time" form:"end_time"`
}

func NewQueryData() QueryData {
	return QueryData{
		PageIndex: 1,
		PageSize:  10,
		Type:      "",
		Search:    "",
		Status:    "",
		Date:      "",
	}
}

func (q *QueryData) Initialize() {
	if q.PageIndex == 0 {
		q.PageIndex = 1
	}
	if q.PageSize == 0 {
		q.PageSize = 10
	}
}

func (q *QueryData) TimeHandle(t int) {
	if t == 0 {
		if q.StartTime != "" {
			q.StartTime = tools.StrToTime(q.StartTime).Format(TimeFormat)
		}
		if q.EndTime != "" {
			q.EndTime = tools.StrToTime(q.EndTime).Format(TimeFormat)
		}
	}
	if t == 1 {
		if q.StartTime != "" {
			q.StartTime = tools.StrToTime(q.StartTime).Format("2006-01-02") + " 00:00:00"
		}
		if q.EndTime != "" {
			q.EndTime = tools.StrToTime(q.EndTime).Format("2006-01-02") + " 23:59:59"
		}
	}
}

func (q *QueryData) StartPage() int {
	return (q.PageIndex - 1) * q.PageSize
}

type LocalTime time.Time

func (t LocalTime) MarshalJSON() ([]byte, error) {
	tTime := time.Time(t)
	return []byte(fmt.Sprintf("\"%v\"", tTime.Format("2006-01-02 15:04:05"))), nil
}

// Value 存储时忽略时间零值
func (t LocalTime) Value() (driver.Value, error) {
	var zeroTime time.Time
	tlt := time.Time(t)
	//判断给定时间是否和默认零时间的时间戳相同
	if tlt.UnixNano() == zeroTime.UnixNano() {
		return nil, nil
	}
	return tlt, nil
}

// Scan 查询时; 0001-01-01 00:00:00 置位 nil null 空
func (t *LocalTime) Scan(v interface{}) error {
	if value, ok := v.(time.Time); ok {
		*t = LocalTime(value)
		return nil
	}
	return fmt.Errorf("can not convert %v to timestamp", v)
}
